package cn.com.libertymutual.saleplat.config;

import io.jsonwebtoken.ExpiredJwtException;

import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.Current;
import cn.com.libertymutual.core.util.uuid.UUIDGenerator;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.core.web.util.RequestUtils;
import cn.com.libertymutual.core.web.util.ResponseUtils;
import cn.com.libertymutual.sp.biz.IdentifierMarkBiz;

/**
 * 本地化信息拦截器
 * 
 * @author bob.kuang
 * 
 */

public class AdminLocaleInterceptor extends HandlerInterceptorAdapter {

	private IdentifierMarkBiz identifierMarkBiz;

	public AdminLocaleInterceptor(IdentifierMarkBiz identifierMarkBiz) {
		this.identifierMarkBiz = identifierMarkBiz;
	}

	private Logger LOG = LoggerFactory.getLogger(getClass());
	
	/**
	 * 本地化字符串在ModelMap中的名称
	 */
	public static final String LOCALE = "locale";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {

		///System.out.println( request.getRequestURI() );
		Device currentDevice = DeviceUtils.getCurrentDevice(request);

		///System.out.println(request.getSession().getId()+"\t"+request.getSession().getAttribute("AABBCC"));
		
		
		///request.getSession().setAttribute("AABBCC", "-lksdflsdjflsdjfldjfl===ss=");
		
		Current.date.set(new Date());
		Current.time.set(System.currentTimeMillis());
		Current.IP.set(RequestUtils.getIpAddr(request));

		Current.uuid.set(UUIDGenerator.getUUID());

		MDC.put("uuid", Current.uuid.get());
		MDC.put("ip", Current.IP.get());
		
		try {
			String[] userCodes = identifierMarkBiz.getUserCodeByToken(request);
			Current.userCode.set(userCodes[0]);
			Current.userCodeBs.set(userCodes[1]);

			MDC.put("device", currentDevice.getDevicePlatform().toString()+userCodes[0]);
		}
		catch( ExpiredJwtException e ) {
			
			String URI = request.getRequestURI();
			if (URI.indexOf("/cxb/nol/") >= 0) {
				LOG.error("JWT过期");
				ServiceResult sr = new ServiceResult("Unauthorized request(403)", Constants.JWT_EXPIRED_ERROR_CODE);
				try {
					ResponseUtils.sendToClient(response, sr);
				} catch (Exception e1) {
					LOG.error(e1.getMessage(), e1);
				}
			
				return false;
			}
		}
		

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// Sevlet容器有可能使用线程池，所以必须手动清空线程变量。
		Current.remove();

		clearMDC();

		// MDCParameters.setSNMDC();
	}

	private void clearMDC() {
		Map<String, String> map = MDC.getCopyOfContextMap();
		if (map != null) {
			map.clear();
		}
		MDC.clear();
	}

}